<template>
  <div style="width:100%;height: 100%;position: absolute;">
  <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px"> 
     <el-input style="width:250px;"
                v-model="queryParams.stationName"
                placeholder="请输入名称"
         clearable
              size="small"
                @keyup.enter.native="handleQuery" />
     <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" style="margin-left:20px;">搜索</el-button>
    </el-form>
   <!-- <baidu-map class="bm-view" ak="ZclHv6FqxCWUHNCHLgyh7fYW" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" @ready="handler">-->
<!--      &lt;!&ndash;比例尺控件&ndash;&gt;-->
<!--      <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>-->
<!--      &lt;!&ndash;缩放控件&ndash;&gt;-->
<!--      <bm-navigation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" ></bm-navigation>-->
<!--      &lt;!&ndash;聚合动态添加的点坐标&ndash;&gt;-->
<!--      <bm-marker-clusterer :averageCenter="true">-->
<!--        <bm-marker v-for="(marker,index) of markers" :key="index"  :position="{lng: marker.longitude, lat: marker.latitude}" @click="viewInfoWindowOpen(marker)">-->
<!--        </bm-marker>-->
<!--      </bm-marker-clusterer>-->
<!--      &lt;!&ndash;信息窗体&ndash;&gt;-->
<!--      <bm-info-window :position="{lng: marker.longitude, lat: marker.latitude}" :title="marker.stationName" :width="400" style="font-size:16px;" :show="marker.show" @close="infoWindowClose(marker)" @open="infoWindowOpen(marker)">-->
<!--        <hr />-->
<!--        <p><span class="left">联&nbsp;&nbsp;系&nbsp;&nbsp;人：</span><span class="right">{{marker.contacts}}</span></p>-->
<!--        <p><span class="left">联系电话：</span><span class="right">{{marker.telephone}}</span></p>-->
<!--        <p><span class="left">联系地址：</span><span class="right">{{marker.address}}</span></p>-->
<!--        <p><span class="left">总运单数：</span><span class="right">{{marker.billNum}}单</span></p>-->
<!--         <div style="display:flex;justify-content:space-between;align-items:center"><p><span class="left">称重总重：</span><span class="right">{{marker.weightTotal}}吨</span></p>-->
<!--        <el-button class="vedioButton" @click="toggleModel">观看视频</el-button></div>-->
<!--      </bm-info-window>-->
<!--    </baidu-map> -->
    <div  id="mapShow"></div>
    <!-- <div class="img-box">
      <img  :src="require('@/assets/image/ditu.png')" />
    </div> -->
        <el-dialog
      title="观看视频"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"

      width="30%"
      :before-close="handleClose">
      <div>
        <div><span class="vedioButton" :class="channelNumber==item.channelNumber?'active':''" v-for="(item,index) in vedioList" :key="index" @click="toggleVedio(item)">{{item.channelName}}</span></div>
         <div >
         <div  id="divPlugin" class="plug"></div>
         <p style="color:red">{{showLoadingText}}</p>
         </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </span>
</el-dialog>
  </div>
</template>

<script>
  import { stationLocation } from "@/api/map/station";
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
  import BmScale from 'vue-baidu-map/components/controls/Scale'
  import BmNavigation from 'vue-baidu-map/components/controls/Navigation'
  import BmMarkerClusterer from  'vue-baidu-map/components/extra/MarkerClusterer'
  import BmMarker from 'vue-baidu-map/components/overlays/Marker'
  import BmInfoWindow from 'vue-baidu-map/components/overlays/InfoWindow'
  export default {
    components: {
      BaiduMap,
      BmScale,
      BmNavigation,
      BmMarkerClusterer,
      BmMarker,
      BmInfoWindow
    },
    data () {
      return {
        center: {lng: 120.321744, lat: 31.499795},
        zoom: 13,
        markers:[],
        marker:{},
        queryParams: {
          stationName: undefined,
        },
        dept:{},
        // 场站信息表格数据
        stationList: [],
        vedioList:[],
            dialogVisible:false,
            ip:'',
            port:'',
            user:'',
            password:'',
            channelNumber:1,
            iRet:0,
            activeVedio:1,
            vedioloading:false,
            showLoadingText:'开始预览',
              map: null,
              icon:require('@/assets/logo/logo.png')
      }
    },
    
    created() {
      const dept = this.$store.getters && this.$store.getters.dept;
      this.dept = dept;
       window.toggleModel=this.toggleModel
    },
     mounted() {      
             this.baiduMap()       



        },
    methods: {
      baiduMap() {
                let that = this
                that.map = new BMap.Map("mapShow",{minZoom:11,maxZoom:14});
                let point = new BMap.Point(120.321744, 31.499795);
                that.map.centerAndZoom(point,11);
                that.map.addControl(new BMap.NavigationControl());
                that.map.enableScrollWheelZoom(); 
                that.map.enableKeyboard();
                that.getStationList()
            },
   
      handler ({BMap, map}) {
        this.getStationList();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        var that=this
        stationLocation(this.queryParams).then(response => {
          this.markers = [];
           this.vedioList=response.data[0].siteCameraList
         
          response.data.forEach((item, i) => {
             item.show = false;
            this.markers.push(item);
             that.openView(item,2)
          });
          // if(this.markers.length > 0){
          //   this.infoWindowOpen(this.markers[0]);
          // }
        
        });
      },
      async getStationList(){
        var that=this
        await stationLocation(this.queryParams).then(response => {
          this.markers = [];
          response.data.forEach((item, i) => {
           
            item.show = false;
            this.markers.push(item);
             //设置标注的经纬度
             if(item.isStationFlag==2){
               that.openView(item,1)
            }
          });

        });
      },
      openView(item,type){
        var that=this
         this.marker = new BMap.Marker(new BMap.Point(item.longitude,item.latitude));
            //把标注添加到地图上
            that.map.addOverlay(this.marker);
            var content = `<div>
             <p><span class="left"><span class="right">${item.stationName}</span></p>
             <p><span class="left">联系电话：</span><span class="right">${item.telephone}</span></p>
             <p><span class="left">联系地址：</span><span class="right">${item.address}</span></p>
             <p><span class="left">总运单数：</span><span class="right">${item.billNum}单</span></p><hr />
             <div style="display:flex;justify-content:space-between;align-items:center"><p><span class="left">称重总重：</span><span class="right">${item.weightTotal}吨</span></p>
             <button class="vedioButton" onclick="toggleModel()">观看视频</button>
             </div></div>
            `;
            var infowindow = new BMap.InfoWindow(content);
            if(type==1){
            this.marker.addEventListener("click",function(){
                this.openInfoWindow(infowindow);
            });
            }else{
            this.marker.openInfoWindow(infowindow)
            }
      },
      infoWindowClose(marker){
        this.marker = marker;
        this.marker.show =false;
        console.info(marker.stationName);
      },
      infoWindowOpen(marker){
        console.info(marker.stationName);
        this.marker = marker;
        this.center={lng: marker.longitude, lat: marker.latitude};
        this.zoom = 15;
        this.marker.show =true;
      },
      viewInfoWindowOpen(marker){
        if(this.markers.length != 1){
          this.marker = marker;
        }
        this.center={lng: marker.longitude, lat: marker.latitude};
        this.zoom = 15;
        this.marker.show =true;
      },
      toggleModel(){
        var that=this
        this.dialogVisible = true
         this.ip=this.vedioList[0].ip;
         this.port=this.vedioList[0].port;

         this.user=this.vedioList[0].userName
         this.password=this.vedioList[0].passWord
         this.channelNumber=this.vedioList[0].channelNumber
         this.vedioloading=true
        setTimeout(function(){
          if (-1 == WebVideoCtrl.I_CheckPluginInstall()) {
		    alert("您还未安装过插件,请先安装WebComponents.exe！");
		     return;
	       }
        //第一步，初始化并嵌入插件
        WebVideoCtrl.I_InitPlugin('100%', '100%',{
          iWndowType: 1,
          cbInitPluginComplete: function () {
            WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
          }
        })
        WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
        WebVideoCtrl.I_ChangeWndNum(1)
         this.showLoadingText='开始预览'
         that.cameraDirectPlay()
        },500)
      },
      toggleVedio(item){
         this.ip=item.ip;
         this.port=item.port;
         this.user=item.userName
         this.password=item.passWord
         this.channelNumber=item.channelNumber
          this.showLoadingText='切换预览'
         if(this.iRet!=-1&&typeof(this.iRet)!=='undefined'){
            this.cameraDirectPlay()
         }else{
             this.iChannelID()
         }

      },
      cameraDirectPlay(){
         var that=this
       // 第二步，登录设备
       this.iRet =  WebVideoCtrl.I_Login(that.ip, 1, that.port, that.user, that.password,{
          success:function (){
            that.showLoadingText = "登录成功！";
            // WebVideoCtrl.I_GetAnalogChannelInfo(that.ip,{async: false})
            //第三步，播放画面
            let iRetPlay=WebVideoCtrl.I_StartRealPlay(that.ip, {
              iStreamType:2,
              iChannelID:that.channelNumber
            })
            if (0 == iRetPlay) {
              that.showLoadingText = "预览成功！";
            } else {
              that.showLoadingText = "预览失败！";
            }
          },error:function(){
            that.showLoadingText = "登录失败！";
          }
        })
        if(typeof(this.iRet)=='undefined'){
          that.showLoadingText = "登录成功";
        }
      },
      iChannelID(){
        var that=this
       var oWndInfo = WebVideoCtrl.I_GetWindowStatus();
       if (oWndInfo != null) {// 已经在播放了，先停止
	        	WebVideoCtrl.I_Stop();
	         }
        let iRet=WebVideoCtrl.I_StartRealPlay(that.ip, {
              iStreamType:2,
              iChannelID:that.channelNumber
            })
            if (0 == iRet) {
              that.showLoadingText = "预览成功！";
            } else {
              that.showLoadingText = "预览失败！";
            }
      },
      handleClose(){
        var oWndInfo = WebVideoCtrl.I_GetWindowStatus()
       this.showLoadingText='开始预览'
      if (oWndInfo != null) {
        var iRet = WebVideoCtrl.I_Stop();
        if (0 == iRet) {
          console.log("停止预览成功")
        } else {
          console.log("停止预览失败！")
        }
      }

        this.dialogVisible = false
        WebVideoCtrl.I_Logout(this.ip)
        console.log('退出成功')
      }
    },
  }
</script>

<style scoped>
  .bm-view {
    width: 100%;
    height: 95%;
    margin-top:5px;
    overflow: hidden;
  }
  div{
    padding:0;
  }
  p{
    font-size: 12px;
    margin:0;
    line-height:20px;
  }
  .right{
    font-size:16;
    font-weight:bold;
  }
   #divPlugin{
    width:100%;
    height:300px;
    background:rgba(0,0,0,0.8);
    padding:0;
  }
.vedioButton{
    cursor: pointer;
  display:inline-block;
  background:skyblue;
  color:#fff;
  padding:5px 15px;
}
.active{
  background:burlywood;
}
  .img-box{
        width:100%;
        height:100%;
  }
  .img-box img{
    width:100%;
    height:100%;
  }
  #mapShow{
    width:100%;
    height:calc(100% - 40px)
  }
</style>
